package cn.chiship.sdk.framework.multipartFile;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * InputStream转为multipartFile工具类
 *
 * @author lijian
 */
public class InputStreamToMultipartFile implements MultipartFile {

	private String originalFilename;

	private String contentType;

	private final byte[] content;

	/**
	 * Create a new MultipartFileDto with the given content.
	 * @param originalFilename the original filename (as on the client's machine)
	 * @param contentType the content type (if known)
	 * @param content the content of the file
	 */
	public InputStreamToMultipartFile(String originalFilename, String contentType, byte[] content) {
		this.originalFilename = (originalFilename != null ? originalFilename : "");
		this.contentType = contentType;
		this.content = (content != null ? content : new byte[0]);
	}

	/**
	 * Create a new MultipartFileDto with the given content.
	 * @param originalFilename the original filename (as on the client's machine)
	 * @param contentType the content type (if known)
	 * @param contentStream the content of the file as stream
	 * @throws IOException if reading from the stream failed
	 */
	public InputStreamToMultipartFile(String originalFilename, String contentType, InputStream contentStream)
			throws IOException {
		this(originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
	}

	@Override
	public String getName() {
		return this.originalFilename;
	}

	@Override
	public String getOriginalFilename() {
		return this.originalFilename;
	}

	@Override
	public String getContentType() {
		return this.contentType;
	}

	@Override
	public boolean isEmpty() {
		return (this.content.length == 0);
	}

	@Override
	public long getSize() {
		return this.content.length;
	}

	@Override
	public byte[] getBytes() throws IOException {
		return this.content;
	}

	@Override
	public InputStream getInputStream() {
		return new ByteArrayInputStream(this.content);
	}

	@Override
	public void transferTo(File dest) throws IOException, IllegalStateException {
		FileCopyUtils.copy(this.content, dest);
	}

	/**
	 * inputStream转multipartFile
	 * @param originalFilename
	 * @param contentType
	 * @param content
	 * @return MultipartFile
	 */
	public static MultipartFile inputStreamConvert(String originalFilename, String contentType, byte[] content) {
		return new InputStreamToMultipartFile(originalFilename, contentType, content);
	}

	/**
	 * inputStream转multipartFile
	 * @param originalFilename
	 * @param contentType
	 * @param contentStream
	 * @return MultipartFile
	 */
	public static MultipartFile inputStreamConvert(String originalFilename, String contentType,
			InputStream contentStream) throws IOException {
		return new InputStreamToMultipartFile(originalFilename, contentType, contentStream);

	}

}
